﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using org.swinchester.windowsevents.core;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace org.swinchester.windowsevents.mongodb
{
    public class MongoMachineTrackingEntityDao : MongoDaoBase, IEventRecordTracker
    {
        private MongoCollection<MongoMachineTrackingEntity> GetCollection()
        {
            return GetMongoDb().GetCollection<MongoMachineTrackingEntity>(config.ComputerEntities);
        }

        private MongoMachineTrackingEntity RegisterComputer(string computerName)
        {
            var ent = new MongoMachineTrackingEntity { Name = computerName, EventRecordId = 0 };
            var collection = GetCollection();
            collection.Insert(ent);
            return ent;
        }

        private MongoMachineTrackingEntity GetComputerEntityByComputerName(string computerName)
        {
            MongoMachineTrackingEntity ent = null;
            var query = Query.EQ("Name", computerName);
            ent = GetCollection().FindOne(query);
            return ent;
        }

        public void UpdateEventRecordId(string computerName, long eventRecordId)
        {
            MongoMachineTrackingEntity ce = GetComputerEntityByComputerName(computerName);
            if (ce == null)
            {
                ce = this.RegisterComputer(computerName);
            }

            var query = Query.EQ("_id", ce.Id);
            var update = Update.Set("EventRecordId", eventRecordId);
            GetCollection().Update(query, update);
        }


        public long GetLastEventRecordId(string computerName)
        {
            long lEventRecordId = 0;
            MongoMachineTrackingEntity ent = GetComputerEntityByComputerName(computerName);
            if (ent != null)
            {
                lEventRecordId = ent.EventRecordId;
            }
            return lEventRecordId;
        }
    }
}
